package com.modular.extra.ai.vision.model;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.c.opt.ComOpt;
import com.modular.extra.ai.FactoryAiOpt;
import com.tool.ToolRedisson;
import ntd.util.frame.javacv.action.bean.VisionModelDo;
import org.redisson.api.RList;

import java.time.Duration;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 离线记录操表
 */
public class OptVisionModel extends ComOpt<VisionModelDo> {

    public OptVisionModel() {
        super("ai_vision_model", FactoryAiOpt.DS_ID);
    }

    /**
     * 查询全部模型列表 - 缓存10分钟
     * 2023.11.28 liuwenju 增加分布式锁，不然总是出现十个重复模型
     * @return
     */
    public List<VisionModelDo> cacheListAll() {
        AtomicReference<RList<VisionModelDo>> aiVisionModelAll = new AtomicReference<>();
        ToolRedisson.me.lock_run("vision_mobel_cache_list", () -> {
            aiVisionModelAll.set(ToolRedisson.me.redisson.getList("aiVisionModelAll"));
            if (aiVisionModelAll.get().isEmpty()) {
                aiVisionModelAll.get().addAll(FactoryAiOpt.OPT_VISION_MODEL.listBean(null));
                aiVisionModelAll.get().expire(Duration.ofSeconds(60 * 10));
            }
        });
        return aiVisionModelAll.get();
    }

    public static void main(String[] args) {
        StaticLog.info(JSONUtil.toJsonStr(new OptVisionModel().cacheListAll()));
    }

    /**
     * 根据模型编码查找模型
     * @param code
     * @return
     */
    public VisionModelDo getByModeCode(String code) {
        return CollUtil.findOne(cacheListAll(), visionModelDo -> visionModelDo.getCode().equals(code));
    }

}